<template>
  <d2-container class="page">
    <div class="index-top">
      <el-button
        v-for="(val, ind) in sectionList"
        :key="ind"
        @click="handleSection(val)"
        :class="{ active: val.id === params.department_id }"
        >{{ val.name }}</el-button
      >
    </div>
    <div class="index-title">
      <div class="index-title-left">
        <div>上传票据</div>
        <span>注：支持票据格式为png、jpg、pdf、zip</span>
      </div>
      <div>
        <el-button @click="getNewspapeList()">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </div>
    <div class="index-list">
      <div class="index-item" v-for="(val, ind) in newspaperList" :key="ind">
        <el-upload
          class="avatar-uploader"
          :class="{ limit: val.images && val.images.length === 6 }"
          list-type="picture-card"
          :action="action"
          :limit="6"
          :file-list="val.images"
          :ref="'unLoad' + ind"
          :on-success="
            (res, file, fileList) =>
              handleAvatarSuccess(res, file, fileList, ind)
          "
          :before-upload="beforeAvatarUpload"
          :on-remove="(file, fileList) => handleOnRemove(file, fileList, ind)"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
          <div slot="file" slot-scope="{ file }" class="img-box">
            <!-- {{  file}} -->
            <img
              v-if="getFileType(file, 'img')"
              class="el-upload-list__item-thumbnail"
              :src="file.response ? file.response.data.image : file.url"
              alt=""
            />
            <img
              v-if="getFileType(file, 'zip')"
              class="el-upload-list__item-thumbnail img-diy"
              src="./image/index_zip.jpg"
              alt=""
            />
            <img
              v-if="getFileType(file, 'pdf')"
              class="el-upload-list__item-thumbnail img-diy"
              src="./image/index_pdf.jpg"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                v-if="getFileType(file, 'imgpdf')"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span
                v-if="getFileType(file, 'zip')"
                class="el-upload-list__item-delete"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-download"></i>
              </span>
              <span
                class="el-upload-list__item-delete"
                @click="handleRemove(file, ind)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <div class="index-item-line"></div>
        <div v-for="v in val.item" class="index-item-input" :key="v.id">
          <span>{{ v.name }}</span>
          <div>
            <el-input
              v-model="v.num"
              type="number"
              min="0"
              class="index-item-num"
            ></el-input>
            <span>份</span>
          </div>
        </div>
      </div>
      <div v-if="!newspaperList.length">暂无数据</div>
    </div>
    <confirm
      v-if="dialogVisibles"
      :dialog-visibles="dialogVisibles"
      @update="updateList"
    ></confirm>
    <el-dialog
      :visible.sync="imgVisible"
      class="edit-dialog preview"
      append-to-body
    >
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </d2-container>
</template>

<script>
import confirm from "./components/confirm";
import { request } from "@/api/_service.js";

export default {
  components: {
    confirm,
  },
  data() {
    return {
      dialogVisibles: false,
      dialogImageUrl: "",
      sectionList: [],
      newspaperList: [],
      params: {
        department_id: "",
      },
      fileType: [
        "image/jpeg",
        "image/png",
        "application/x-zip-compressed",
        "application/pdf",
      ],
      action: process.env.VUE_APP_API + "/mapi/common/uploadFile",
      content: [],
      imgVisible: false,
    };
  },
  mounted() {
    this.getSection();
  },
  beforeDestroy() {
    // clearInterval(this.timeInterval)
  },
  methods: {
    getSection() {
      request({
        url: "/mapi/department/index",
        method: "post",
      }).then((res) => {
        console.log(res, "/mapi/department/index");
        this.sectionList = res.data;
        if (this.sectionList.length) this.handleSection(this.sectionList[0]);
      });
    },
    getNewspapeList() {
      request({
        url: "/mapi/newspaper/index",
        method: "post",
        data: this.params,
      }).then((res) => {
        this.newspaperList = res.data.map((val) => {
          return {
            ...val,
            images: [],
          };
        });
        // console.log(res, '/mapi/department/index')
      });
    },
    handlePictureCardPreview(file) {
      const type = this.getFileType(file);
      if (type === "pdf" || type === "zip") return window.open(file.url);
      this.dialogImageUrl = file.response ? file.response.data.image : file.url;
      this.imgVisible = true;
    },
    getFileType(file, fileType) {
      let type = "";
      if (file.response) {
        type = file.name.split(".").reverse()[0];
      } else {
        type = file.extension;
      }
      if (fileType === "img") return type === "jpg" || type === "png";
      else if (fileType === "zip") return type === "zip";
      else if (fileType === "pdf") return type === "pdf";
      else if (fileType === "imgpdf")
        return type === "pdf" || type === "jpg" || type === "png";
      else if (!fileType) return type;
    },
    handleRemove(file, ind) {
      this.$refs["unLoad" + ind][0].handleRemove(file);
      // const ind = this.detailsData.imgs.findIndex((v)=>v.url === file.url || file.response === v.response)
      // this.detailsData.imgs.splice(ind,1)
      // console.log(ind)
    },
    submitNewspape() {
      // return console.log(this.newspaperList,'newspaperList')
      const content = this.newspaperList.map((val) => {
        return {
          newspaper_id: val.id,
          images: val.images,
          item: val.item,
        };
      });
      request({
        url: "/mapi/newspaper/submitNewspaper",
        method: "post",
        data: {
          content: JSON.stringify(content),
        },
      }).then((res) => {
        this.$message.success("添加成功！");
        // console.log(res, '/mapi/department/index')
      });
    },
    handleSubmit() {
      let isPass = true
      let allNull = true
      this.newspaperList.map((val) => {
        let hasImgs = false
        let hasNum = false;
        if(val.images.length > 0) hasImgs = true
        val.item.map((v) => {
          if (v.num > 0 ) hasNum = true;
        });
        if((hasNum && !hasImgs) || (!hasNum && hasImgs)) isPass = false
        if(hasNum && hasImgs) allNull = false
      });
      if (!isPass || allNull) {
        return this.$message.error("请上传图片并填写数量！");
      }
      this.dialogVisibles = true;
    },

    updateList(val) {
      this.dialogVisibles = false;
      if (val) {
        this.submitNewspape();
      }
    },
    handleSection(val) {
      this.params.department_id = val.id;
      this.getNewspapeList();
    },
    handleOnRemove(file, fileList, ind) {
      // this.newspaperList[ind].images.splice(0,6)
      this.newspaperList[ind].images = fileList.map((v) =>
        v.response ? v.response.data.image : v.url
      );
    },
    handleAvatarSuccess(res, file, fileList, ind) {
      const url = [res.data.image];
      this.newspaperList[ind].images = fileList.map((v) =>
        v.response ? v.response.data.image : v.url
      );
      console.log(
        this.newspaperList[ind],
        "this.newspaperList[ind]this.newspaperList[ind]"
      );
    },
    beforeAvatarUpload(file) {
      console.log(
        file.type,
        "----png、jpg、pdf、zippng、jpg、pdf、zippng、jpg、pdf、zip"
      );
      // const isJPG = file.type === 'image/jpeg';
      const limitType = this.fileType.includes(file.type);
      if (!limitType) {
        this.$message.error("请上传png、jpg、pdf、zip格式的票据!");
      }

      return limitType;
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  font-size: 18px;
  .img-box {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    .img-diy {
      width: 80%;
      height: auto;
    }
  }
  .index-top {
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    padding-bottom: 30px;

    .el-button {
      height: 50px;
      font-size: 18px;
      border-radius: 10px;
      border: 1px solid rgba(58, 58, 58, 0.2);

      &.active {
        color: #409eff;
        border-color: #c6e2ff;
        background-color: #ecf5ff;
      }

      & + .el-button {
        margin-left: 20px;
      }
    }
  }

  .index-title {
    display: flex;
    justify-content: space-between;
    padding-top: 30px;
    margin-bottom: 30px;

    .el-button {
      width: 112px;
      height: 50px;
      font-size: 18px;
      border-radius: 10px;
      border: 1px solid rgba(58, 58, 58, 0.2);

      & + .el-button {
        margin-left: 20px;
      }

      &.el-button--primary {
        background: #036af2 !important;
        &:hover{
          color: #c6e2ff;
        }
      }
    }

    .index-title-left {
      & > div {
        line-height: 25px;
      }

      & > span {
        line-height: 22px;
        color: #828592;
        font-size: 16px;
      }
    }
  }

  .index-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    // display: grid;
    // grid-template-columns: 274px; /* 最小200px，自动填充剩余空间 */
    // grid-auto-rows: 208px;
    // grid-gap: 16px; /* 网格间隙 */
    // width: 100%;

    .index-item {
      box-sizing: border-box;
      width: 274px;
      height: fit-content;
      border-radius: 10px;
      border: 1px solid rgba(0, 0, 0, 0.08);
      padding: 14px;
      .index-img {
        width: 76px;
        height: 76px;
        border-radius: 10px;
        margin-right: 10px;
      }

      .avatar-uploader {
        min-height: 89px;
        &::v-deep .el-upload--picture-card {
          width: 76px;
          height: 76px;
          line-height: 76px;
          background: #f4f8fb;
        }

        &.limit {
          &::v-deep .el-upload--picture-card {
            display: none;
          }
        }

        &::v-deep .el-upload-list--picture-card {
          .el-upload-list__item {
            width: 76px;
            height: 76px;
          }
          .el-upload-list__item:nth-child(3n) {
            margin-right: 0;
          }
        }

        .el-upload {
          border: 1px dashed #d9d9d9;
          background: #f4f8fb;
          border-radius: 10px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
        }

        .el-upload:hover {
          border-color: #409eff;
        }

        .avatar-uploader-icon {
          font-size: 18px;
          color: #8c939d;
          width: 76px;
          height: 76px;
          line-height: 76px;
          text-align: center;
          font-weight: bold;
        }
      }
    }
  }
  .index-item-line {
    border: 1px solid rgba(0, 0, 0, 0.08);
    margin-bottom: 7px;
  }
  .index-item-input {
    font-size: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 7px 0;
    & > div {
      display: flex;
      justify-content: space-between;
      align-items: center;
      span {
        font-size: 14px;
        color: #3a3a3a;
        margin-left: 8px;
      }
      .index-item-num {
        &::v-deep .el-input__inner {
          width: 78px;
          height: 25px;
          background: #f4f8fb;
          border-color: #f4f8fb;
        }
      }
    }
  }
}
</style>
